<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表表格 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbotton',i1 == 0 ? 'bdtop':'','vcenter']" 
                    v-for="(item1, i1) in scope.row.children" 
                    :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="closeTag(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children"
                        :key="item2.id"
                        :class="[i2 == 0 ? '':'bdtop','vcenter']">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" 
                            closable
                            @close="closeTag(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                    <!-- {{item2.authName}} -->
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag v-for="(item3) in item2.children"
                            :key="item3.id"
                            type="warning" 
                            closable
                            @close="closeTag(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre>{{scope.row}}</pre>
          </template> 
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" 
                        icon="el-icon-edit"
                        size="mini"
                        @click="showEditDialog(scope.row.id)">编辑
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger"
                      icon="el-icon-delete"
                      size="mini"
                      @click="deleteList(scope.row.id)">删除
            </el-button>
            <!-- 分配权限按钮 -->
            <el-button type="warning"
                      icon="el-icon-setting"
                      size="mini"
                      @click="showSetRightsDialog(scope.row)">分配权限
            </el-button>
          </template> 
          
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框区域 -->
    <el-dialog title="添加角色" 
               :visible.sync="addDialogVisible" 
               width="50%"
               @close="addDialogClosed">
      <!-- 主体内容区域 -->
      <el-form :model="addForm" 
               :rules="addFormRules" 
               ref="addFormRef" 
               label-width="80px ">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>

        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">
          取 消
        </el-button>
        <el-button type="primary" 
        @click="addRoles">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框区域 -->
    <el-dialog title="编辑角色" 
               :visible.sync="editDialogVisible" 
               width="50%"
               @close="editDialogClosed">
      <!-- 主体内容区域 -->
      <el-form :model="editForm" 
               :rules="editFormRules" 
               ref="editFormRef" 
               label-width="80px ">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>

        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">
          取 消
        </el-button>
     
        <el-button type="primary" 
        @click="editRoles()">
          确 定
        </el-button>
      </span>
    </el-dialog>
    
    <!-- 分配权限对话框区域 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setDiglogClose">
      <el-tree
        :data="setRightsTree"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="checkedKey"
        ref="treeRef">
      </el-tree>
      <span slot="footer" class="dialog-footer">
      <el-button @click="setRightsDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
  export default{
    data(){
      return{
        // 角色列表
        rolesList:[],
        // 编辑角色对话框显示
        editDialogVisible:false,
        // 添加角色对话框显示
        addDialogVisible:false,
        // 设置权限对话框显示
        setRightsDialogVisible:false,
        // 查询到的角色信息数据
        editForm:{},
        // 添加角色数据存储
        addForm:{},
        // 修改编辑角色列表规则
        editFormRules: {
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
          ],
          roleDesc: [
            { required: true, message: '请输入角色描述', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
          ]
        },
        // 添加角色列表规则
        addFormRules: {
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
          ],
          roleDesc: [
            { required: true, message: '请输入角色描述', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
          ]
        },
        // 分配权限的树形表单
        setRightsTree: [],
        // 默认的权限列表的对应关系
        defaultProps:{
          children:'children',
          label:'authName'
        },
        // 默认勾选的tree数组
        checkedKey:[],
        // 分配权限时用到的角色id
        roleId:''
      }
    },
    created(){
      this.getRolesList()
    },
    methods: {
      // 获取角色列表 
      async getRolesList(){
        const { data:res } = await this.$http.get('roles')
        if(res.meta.status !== 200){
          // 获取失败
          return this.$message.error('获取角色列表失败！')
        }
        // 获取成功
        this.rolesList = res.data
        // console.log(res)
      },
      // 显示编辑角色对话框
      async showEditDialog(id) {
        // 根据id查询角色
        const { data:res } = await this.$http.get('roles/' + id)
        if(res.meta.status !== 200){
          return this.$message.error('查询角色失败！')
        }
        this.editForm = res.data
        this.editDialogVisible = true
      },
      // 关闭编辑角色对话框时触发
      editDialogClosed(){
        this.$refs.editFormRef.resetFields()
      },
      // 关闭添加角色对话框时触发
      addDialogClosed(){
        this.$refs.addFormRef.resetFields()
      },
      // 添加角色
      async addRoles(){
        // 发送添加角色请求
        const {data:res} = await this.$http.post('roles', this.addForm)
        if(res.meta.status !== 201){
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功！')
        this.getRolesList()
        this.addDialogVisible = false
      },
      // 点击确定时修改角色数据
      editRoles(){
        this.$refs.editFormRef.validate(async valid => {
          if(!valid){
            return this.$message.error('请检查信息！')
          }
          const {data:res} = await this.$http.put('roles/' + this.editForm.roleId, {
            roleName : this.editForm.roleName,
            roleDesc : this.editForm.roleDesc
          })
          console.log(this.editForm)
          if(res.meta.status !== 200){
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('修改角色信息成功！')
          this.editDialogVisible = false
          this.getRolesList()
        })
      },
      // 删除用户角色
      async deleteList(id){
        const data = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => {
          return error
        })
        if(data !== 'confirm'){
          return this.$message.info('取消删除用户')
        }
        const {data:res} = await this.$http.delete('roles/' + id)
        // console.log(res)
        if(res.meta.status !== 200){
          return this.$message.error('删除角色信息失败！')
        }
        this.$message.success('删除角色信息成功！')
        this.getRolesList()
      },
      // 关闭权限标签
      async closeTag(role, rightId){
        const data = await this.$confirm('此操作将删除用户该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => {
                return error
        })
        // 取消删除权限
        if(data !== 'confirm'){
          return this.$message.info('取消删除权限！')
        }
        
        const {data:res} = await this.$http.delete('roles/' + role.id + '/rights/' + rightId)
        console.log(res)
        if(res.meta.status !== 200){
          return this.$message.error('删除权限失败！')
        }
        this.$message.success('删除权限成功！')
        // 会刷新整个页面，不推荐使用
        // this.getRolesList()
        role.children = res.data
      },
      //展示分配权限对话框
      async showSetRightsDialog(role){
        const {data:res} = await this.$http.get('rights/tree')
        this.roleId = role.id
        if(res.meta.status !== 200){
          return this.$message.error('获取权限列表失败！')
        }
        this.setRightsTree = res.data
        // 递归获取三级节点id
        this.getLeafKeys(role, this.checkedKey)
        this.setRightsDialogVisible = true
      },
      // 通过递归的形式 获取角色下所有的三级权限的ID 并保存到数组中
      getLeafKeys(node, arr){
        if(!node.children){
          return arr.push(node.id)
        }

        node.children.forEach(item => {
          this.getLeafKeys(item, arr)
        })
      },
      // 分配权限对话框关闭时，清空tree
      setDiglogClose() {
        this.checkedKey = []
      },
      // 点击分配权限对话框确定按钮时，进行权限分配
      async setRights() {
        const keys = [
          ...this.$refs.treeRef.getHalfCheckedKeys(),
          ...this.$refs.treeRef.getCheckedKeys()
        ]
        const isStr = keys.join(',')
        const {data:res} = await this.$http.post('roles/' + this.roleId + '/rights', {
          rids:isStr
        })
        if(res.meta.status !== 200) {
          return this.$message.error('分配权限失败！')
        }
        this.$message.success('分配权限成功！')
        this.getRolesList()
        this.setRightsDialogVisible = false
      }
    }
  }
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbotton {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
